const { $util } = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isswitch: false,
    address: '',
    lat: '',
    lng: '',
    topicid: '', // 话题id
    pid: '', // 评论id
    typ: 1, // 1-初始评论 2-回复 3追加回复
    img: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(options);
    $util.request({
      url: 'entry/wxapp/group.topic.gettoppiclist',
      data: {},
      showLoading: false,
      success: (res) => {
        this.setData({
          list: res.data,
        });
      },
    });
  },
  bindInpVal(e) {
    this.setData({
      content: e.detail.value,
    });
  },
  chooseTopic(e) {
    this.setData({
      topicid: e.currentTarget.dataset.id,
    });
  },
  switchChange(e) {
    this.setData({
      isswitch: e.detail.value,
    });
    if (e.detail.value) {
      this.chooseLocation();
    } else {
      this.setData({
        address: '',
      });
    }
  },
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        if (res.address) {
          this.setData({
            address: res.address,
            lat: res.latitude,
            lng: res.longitude,
          });
        } else {
          this.setData({
            isswitch: false,
          });
        }
      },
      fail: (res) => {
        this.getSetting();
      },
    });
  },
  getSetting() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          wx.openSetting({
            success: (res) => {
              console.log('authorize', res);
              if (res.authSetting['scope.userLocation']) {
                this.chooseLocation();
              } else {
                this.setData({
                  isswitch: false,
                });
              }
            },
          });
        }
      },
    });
  },
  isprevent: false,
  submit(e) {
    if (!this.data.content) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
      });
      return;
    }
    if (this.isprevent) return;
    this.isprevent = true;
    $util.request({
      url: 'entry/wxapp/group.comment.addcomment',
      data: {
        topicid: this.data.topicid,
        content: this.data.content,
        pic: this.data.img,
        isshow: this.data.isswitch,
        site: this.data.address,
        lat: this.data.lat,
        lng: this.data.lng,
        type: this.data.typ, // 1-初始评论 2-回复 3追加回复
        pid: this.data.pid,
      },
      showLoading: false,
      success: (res) => {
        wx.showToast({
          title: '发布成功',
          icon: 'none',
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      },
      complete: () => {
        setTimeout(() => {
          this.isprevent = false;
        }, 1000);
      },
    });
  },
  imgsOnChange(e) {
    this.setData({
      img: e.detail,
    });
  },
});
